/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package TweetRay.Backgrounds;

import Raytracing.Constants;
import processing.core.PImage;
import processing.core.PVector;

/**
 *
 * @author Matt
 */
public class ImageBackground extends Background {

    PImage eMap;

    public ImageBackground(PImage image) {
        eMap = image;
    }

    public void getColor(PVector dir, PVector ret) {


        float phi = (float) Math.atan2(dir.z, dir.x);
        if (phi < 0) {
            phi += Constants.TWO_PI;
        }
        phi /= Constants.TWO_PI;

        float theta = (float) Math.acos(dir.y);

        theta /= Constants.PI;
        theta = 1.f - theta;

        if (theta >= 1) {
            theta = 1;
        }
        if (phi >= 1) {
            phi = 1;
        }
        if (theta <= 0) {
            theta = 0;
        }
        if (phi <= 0) {
            phi = 0;
        }

        theta *= eMap.height;
        phi *= eMap.width;


        int thetai = (int) theta;
        int phii = (int) phi;

        int col = 0;
        try {
            col = eMap.pixels[thetai * eMap.width + phii];
        } catch (Exception e) {
            System.out.println(theta + ":" + phi);
        }

        ret.set((col >> 16) & 0xff,
                (col >> 8) & 0xff,
                (col) & 0xff);


        ret.div(255.f);


    }
}
